#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by zhangyanqi on 2018/3/14

import requests
from bs4 import BeautifulSoup


class Core(object):
    # url
    loginUrl = "http://www.livedu.com.cn/ispace3.0/mooc/login.do"
    getVedioUrl = "http://www.livedu.com.cn/ispace3.0/xsxx/queryXsxx.do"
    setVedioWatchedUrl = "http://www.livedu.com.cn/ispace3.0/xsxx/updKcspSqzt.do"

    # 参数限制
    __slots__ = ("account", "pwd", "sessionId", "requsetSession")

    def __init__(self):
        account = input("Enter your account:")
        self.account = account
        pwd = input("Enter your password:")
        self.pwd = pwd
        session = requests.Session()
        session.trust_env = False
        self.requsetSession = session

    def get_cookie(self):
        '''
        获得浏览器cookie
        :param acount: 用户账号
        :param pwd: 用户密码
        :return: cookie
        '''

        '''
        例子:
        POST http://www.livedu.com.cn/ispace3.0/mooc/login.do

        Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
        Accept-Encoding: gzip, deflate
        Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
        Connection: keep-alive
        Content-Length: 58
        Content-Type: application/x-www-form-urlencoded
        Host: www.livedu.com.cn

        yhdlm=${用户账号}&yhmm={用户密码}&loginFlag=login_new
        '''

        # 参数
        payload = {'yhdlm': self.account, 'yhmm': self.pwd, "loginFlag": "login_new"}
        response = None
        try:
            response = self.requsetSession.post(self.loginUrl, data=payload)
        except Exception as e:
            print("获得cookie出错了" + e.__str__())
        cookies = response.cookies
        sesionId = cookies.get("JSESSIONID")
        self.sessionId = sesionId
        print("获得cookie成功-{}".format(self.sessionId))

    def set_vedio_watched(self, id, lmid, lbdm):

        '''
        :param url: 需要标记为已看的视频所在的网页地址
        :return: None
        '''

        if (self.sessionId == None):
            print("session不存在")
            return

        """
        获得视屏页面
        get  http://www.livedu.com.cn/ispace3.0/xsxx/queryXsxx.do?id=208&lmid=4941&lbdm=0
        Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
        Accept-Encoding: gzip, deflate
        Accept-Language: zh,en;q=0.9,zh-TW;q=0.8
        Cache-Control: max-age=0
        Connection: keep-alive
        DNT: 1
        Host: www.livedu.com.cn
        """
        session_id = "JSESSIONID=" + self.sessionId
        # head
        headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                   "Accept-Encoding": "gzip, deflate",
                   "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
                   "Cookie": session_id
                   }
        # 参数
        url = self.getVedioUrl + "?id=" + str(id) + "&lmid=" + str(lmid) + "&lbdm=" + str(lbdm)
        response = None
        try:
            response = self.requsetSession.get(url, headers=headers)
        except Exception as e:
            print("出错了" + e.__str__())
        # 解析html
        page = response.text
        # print(page)
        soup = BeautifulSoup(page, 'html.parser')
        div = soup.find(id="bfqdiv_1")
        js = (div.img)["onclick"]
        js = js[20:len(js) - 1]
        js = js.split(",")[1]
        streamName = js[1:len(js) - 1]

        """
        Accept	*/*
        Accept-Encoding	gzip, deflate
        Accept-Language	zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
        Connection	keep-alive
        Content-Length	198
        Content-Type	application/x-www-form-urlencoded; charset=UTF-8
        Cookie	JSESSIONID=B795F45213C655BBA572CEA62B108AF8
        Host	www.livedu.com.cn
        Referer	http://www.livedu.com.cn/ispac…sxx.do?id=208&lmid=4927&lbdm=0
        User-Agent	Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/59.0
        X-Requested-With	XMLHttpRequest

        kcdm=208&zjdm=5342&streamName=Act-ss-mp4-hd%2F6946bcbdfa5c4852a28ccca86b6722c1%2FWS00V02-%25E5%2585%25A8%25E8%25AF%25BE%25E7%25A8%258B%25E5%2586%2585%25E5%25AE%25B9%25E5%25AF%25BC%25E5%25AD%25A6aaa.mp4
        """

        headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                   "Accept-Encoding": "gzip, deflate",
                   "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
                   "X-Requested-With": "XMLHttpRequest",
                   "Cookie": session_id
                   }

        payload = {'kcdm': id, "zjdm": lmid, "streamName": streamName}
        response = None
        try:
            response = self.requsetSession.post(self.setVedioWatchedUrl, headers=headers, data=payload)
        except Exception as e:
            print("出错了" + e.__str__())

